-- UICompoundSpell
-- Create by huanghr
-- 合成卷界面

-- UICompoundSpell继承自Layer
UICompoundSpell = class("UICompoundSpell", function(spellId)
    return cc.Layer:create();
end);

function UICompoundSpell.create(spellId)
    return UICompoundSpell.new(spellId);
end

-- 构造函数
function UICompoundSpell:ctor(spellId)
    -- 初始化
    self:setName("UICompoundSpell");
    local node = cc.CSLoader:createNode("layout/risker_equip/CompoundSpell.csb");
    self:addChild(node);
    self.node = node;

    self.spellId = spellId;

    self.CT = node:getChildByName("CT");
    self.BT = node:getChildByName("BT");

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 注册事件回调
    self:registerEventCallback();

    -- 适配
    self:resize();
end

-- 注册事件回调
function UICompoundSpell:registerEventCallback()
    -- 关注卷轴合成事件
    EventMgr.register("UICompoundSpell", event.COMPOUND_SPELL, function(args)
        self:redraw();

        local lightNode = findChildByName(self.CT, "product_node/product_spell");
        lightNode:removeAllChildren();

        if type(args.amount) == "number" and args.amount > 1 then
            playEffect(lightNode, 1231, 124, -61,  nil, 0.6);
        else
            playEffect(lightNode, 1180, 124, -61,  nil, 0.6);
        end

        -- 文字提示
        local name = ItemM.query(args.spell_id, "name");
        alert(string.format(getLocStr("compound_spell_tip"), name, args.amount));
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            EventMgr.removeAll("UICompoundSpell");
        end
    end);
end

-- 注册点击事件
function UICompoundSpell:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UICompoundSpell");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 这两个按钮都是直接合成一个
    local btnRight = findChildByName(self.node, "CT/btn_right");
    local btnCenter = findChildByName(self.node, "CT/btn_center");

    -- 直接合成一个
    local function onCompoundClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
           self:tryCompound(1);
        end
    end
    btnRight:addTouchEventListener(onCompoundClick);
    btnCenter:addTouchEventListener(onCompoundClick);

    -- 合成多个
    local btnLeft = findChildByName(self.node, "CT/btn_left");
    local function onMultiCompoundClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
           self:tryCompound();
        end
    end
    btnLeft:addTouchEventListener(onMultiCompoundClick);

    -- 点击对应卷轴页面可以显示具体信息
    local srcSpellIcon = findChildByName(self.CT, "material_node/spell_img_2");
    local dstSpellIcon = findChildByName(self.CT, "product_node/product_spell");
    local function onSpellClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            require "game/ui/form/spell/UISpellOperation";
            -- 打开卷轴操作界面
            UIMgr.getCurrentScene():removeFormByName("UISpellOperation");
            local uiSpellOperation = UISpellOperation.create(sender.spellId, true);
            UIMgr.getCurrentScene():addForm(uiSpellOperation);
        end
    end
    srcSpellIcon:addTouchEventListener(onSpellClick);
    dstSpellIcon:addTouchEventListener(onSpellClick);
end

-- 重绘
function UICompoundSpell:redraw()
    -- 绘制标题
    local titleLabel = findChildByName(self.CT, "title_label");
    local subTitle = findChildByName(self.CT, "sub_title");

    local name = ItemM.query(self.spellId, "name");

    local title = string.format(getLocStr("magic_spell"), name);

    -- 设置标题文本
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(title);

    -- 设置副文本标题
    TextStyleM.setTextStyle(subTitle, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);

    -- 编辑文本(副标题)，获得消耗
    local cost = FormulaM.invoke("CALC_COMPOUND_SPELL_COST", self.spellId);

    local costRune = cost["rune"];

    -- TODO:根据cost来显示副标题文本。合成闪电链卷轴
    local runeNum = tonumber(costRune[3]);
    local runeId = costRune[2];
    local runeName = ItemM.query(runeId, "name");
    local productName = ItemM.query(self.spellId, "name");

    local hasRune = ItemM.getAmount(ME.user, runeId);

    -- 消耗
    local costText = string.format(getLocStr("compound_spell_cost_rune"), runeName, hasRune, runeNum);
    local compoundText = string.format(getLocStr("compound_spell_text"), productName);

    if hasRune < runeNum then
        costText = "[red]".. costText .."[-]";
    else
        costText = "[blue]".. costText .."[-]";
    end

    local subText = compoundText .. costText;

    applyString(subTitle, subText);

    -- TODO：根据合成个数，选择按钮形式
    local amount = self:getCompoundAmount(cost);

    local btnLeft = findChildByName(self.node, "CT/btn_left");
    local btnRight = findChildByName(self.node, "CT/btn_right");
    local btnCenter = findChildByName(self.node, "CT/btn_center")

    if amount > 1 then
        -- 显示两个小按钮
        btnCenter:setVisible(false);
        btnLeft:setVisible(true);
        btnRight:setVisible(true);
        TextStyleM.setTextStyle(btnLeft, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnLeft:setTitleText(string.format(getLocStr("btn_text_compound_spell"), amount));

        TextStyleM.setTextStyle(btnRight, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnRight:setTitleText(string.format(getLocStr("btn_text_compound_spell"), 1));
    elseif amount == 1 then
        -- 只显示一个大的按钮
        btnCenter:setVisible(true);
        btnLeft:setVisible(false);
        btnRight:setVisible(false);

        TextStyleM.setTextStyle(btnCenter, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnCenter:setTitleText(getLocStr("btn_text_compound_spell_2"));
    else
        btnCenter:setVisible(true);
        btnLeft:setVisible(false);
        btnRight:setVisible(false);

        TextStyleM.setTextStyle(btnCenter, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btnCenter:setTitleText(getLocStr("btn_text_compound_spell_2"));

        -- 按钮不能点击
        btnCenter:setBright(false);
        btnCenter:setTouchEnabled(false);
    end

    -- 显示卷轴图标
    local materialSpell = cost["spell"];

    local materialNode = findChildByName(self.CT, "material_node");
    local materialIcon1 = findChildByName(materialNode, "spell_img_1");
    local materialIcon2 = findChildByName(materialNode, "spell_img_2");

    local icon = ItemM.query(materialSpell[2], "icon");
    local materialIconPath = getItemIconPath(icon);

    materialIcon2.spellId = materialSpell[2];

    materialIcon1:loadTexture(materialIconPath);
    materialIcon2:loadTexture(materialIconPath);

    -- 显示卷轴数量
    local numLabel = findChildByName(materialNode, "amount_label");
    local hasAmount = ItemM.getAmount(ME.user, materialSpell[2]);
    local needAmount = materialSpell[3];

    local numText = "%d/%d";
    if needAmount > hasAmount then
        numText = "[light_red]%d/%d[-]"
    end

    numText = string.format(numText, hasAmount, needAmount);

    TextStyleM.setTextStyle(numLabel, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -1);
    applyString(numLabel, numText);

    -- 所合成卷轴图标和阶位
    local productNode = findChildByName(self.CT, "product_node");
    local productIcon = findChildByName(productNode, "product_spell");

    local iconPath = getItemIconPath(ItemM.query(self.spellId, "icon"));
    productIcon:loadTexture(iconPath);
    productIcon.spellId = self.spellId;

    local productRank = ItemM.query(self.spellId, "rank");
    local starNode = findChildByName(productNode, "star_node");

    local layer = createStarLayer(productRank, "images/ui/symbol/star_little.png", "center", -0.6);
    if layer then
        starNode:removeAllChildren();
        starNode:addChild(layer);
    end
end

-- 计算当前可以合成的个数
function UICompoundSpell:getCompoundAmount(cost)
    -- 计算各种消耗能合成数量，取最低值
    local costRune = cost["rune"];
    local costSpell = cost["spell"];

    local runeId = costRune[2];
    local needRuneNum = costRune[3];

    local amount1 = math.modf(ItemM.getAmount(ME.user, runeId) / needRuneNum);

    local spellId = costSpell[2];
    local spellNum = costSpell[3];

    local amount2 = math.modf(ItemM.getAmount(ME.user, spellId) / spellNum);

    local amount = math.min(amount1, amount2);

    return amount;
end

-- 合成卷轴
function UICompoundSpell:tryCompound(num)
    local amount = num;
    if num == nil then
        local cost = FormulaM.invoke("CALC_COMPOUND_SPELL_COST", self.spellId);
        amount = self:getCompoundAmount(cost);
    end

    -- 判断能否合成
    if SpellM.canCompoundSpell(self.spellId, amount) then
        DungeonActionM.go("do_compound_spell", amount, self.spellId);
    else
        return false;
    end
end

-- 适配
function UICompoundSpell:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end